package com.erbao.io.netty.refactor.transport;

import com.erbao.IoUtil;
import com.erbao.io.netty.refactor.rpc.Dispatcher;
import com.erbao.io.netty.refactor.rpc.protocol.MyContent;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledDirectByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;

/**
 * 自定义 http 请求处理
 * @author CaoBaoYin
 * @since 23/9/4 16:19
 */
public class MyHttpRequestHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // msg 经过两次处理后 是一个完整request
        FullHttpRequest request = (FullHttpRequest) msg;
        System.out.println(request.toString()); // consumer url


        MyContent myContent = IoUtil.getContent (request.content());
        Object result = Dispatcher.dispatcher.getResult(myContent);

        MyContent respContent = new MyContent();
        respContent.setResponseObj(result);
        byte[] respBytes = IoUtil.serialize(respContent);
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0,
                HttpResponseStatus.OK,
                Unpooled.copiedBuffer(respBytes));
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, respBytes.length);

        // http协议，header+body
        ctx.writeAndFlush(response);

        super.channelRead(ctx, msg);
    }
}
